package studio.raptor.extractor.segment.config;


import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import studio.raptor.extractor.segment.properties.HttpConnectionProperties;

/**
 * Created by liuyong8 on 2017/7/29.
 */
@Configuration
public class HttpConnectionConfig {

    @Bean
    @ConfigurationProperties(prefix = "extractor.http")
    public HttpConnectionProperties httpConnectionProperties() {
        return new HttpConnectionProperties();
    }

    @Bean
    public ClientHttpRequestFactory httpRequestFactory() {
        return new HttpComponentsClientHttpRequestFactory(httpClient());
    }

    @Bean
    @ConditionalOnBean(HttpConnectionProperties.class)
    public PoolingHttpClientConnectionManager poolingHttpClientConnectionManager() {
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", SSLConnectionSocketFactory.getSocketFactory())
                .build();
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
                registry);
        connectionManager.setMaxTotal(httpConnectionProperties().getMaxTotal());
        connectionManager.setDefaultMaxPerRoute(httpConnectionProperties().getDefaultMaxPerRoute());
        return connectionManager;
    }

    @Bean
    @ConditionalOnBean(HttpConnectionProperties.class)
    public HttpClient httpClient() {
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(httpConnectionProperties().getSocketTimeout())
                .setConnectionRequestTimeout(httpConnectionProperties().getConnectionRequestTimeout())
                .setConnectTimeout(httpConnectionProperties().getConnectTimeout())
                .build();
        return HttpClientBuilder.create()
                .setDefaultRequestConfig(requestConfig)
                .setConnectionManager(poolingHttpClientConnectionManager())
                .build();
    }
}
